package com.qf.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qf.web.common.R;
import com.qf.web.pojo.Student;
import com.qf.web.service.StudentService;
import com.qf.web.service.impl.StudentServiceImpl;

import javax.naming.Name;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.Style;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

@WebServlet("/studentsPageData")
public class StudentsListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //接受模糊查询数据
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");

        Student student = new Student();
        student.setName(name);
        student.setSex(sex);
        student.setAddress(address);
        student.setPhone(phone);


        String page = req.getParameter("page");
        String limit = req.getParameter("limit");

        StudentService studentService = new StudentServiceImpl();
        /*
        * 因为前端layui的 数据列表接受的数据格式 默认是
        * {
        * "code" : 0
        * "msg" : ""
        * "count":1000
        * "data":[{},{}]
        * }
        * 所以 后台需要拼一个这样的JSON串
        * 所以咱们定义了一个 R类
        *
        * private Integer code；
        *
        * private String msg；
        *
        * private T data；
        *
        * private long count；
        *
        * 利用fastjson 等工具类  直接把Java对象转为json格式的字符串 返回给前端
        * 前端能够自动解析
        *
        * */
        int pageNum = Integer.parseInt(page);
        int pageSize = Integer.parseInt(limit);
        R<List<Student>> r  = studentService.getPageData(pageNum, pageSize, student);

        //R<List<Student>> r = new R();
        //
        //r.setData(student);
        //r.setMsg("学生列表数据");
        //r.setCode(0);
        //r.setCount(2);

        //fastjson把java对象转为json串
        String s = JSON.toJSONString(r);

        //可以使用下面工具类
        //String s = FastJsonUtils.convertObjectToJSON(r);
        resp.getWriter().println(s);
    }
}
